package com.atguigu03.threadsafe.runnablesafe;

/**
 * ClassName: WindowTest
 * Package: com.atguigu03.threadsafe.notsafe
 * Description:通过实现Runnable进行售票练习,同时使用同步代码块解决线程安全问题
 *
 * @Author ZY
 * @Create 15:39
 * @Version 1.0
 */


class SaleTicket implements Runnable {

    int ticket = 100;//票数
//    Object obj = new Object();
//    Dog dog = new Dog();

    @Override
    public void run() {

        while (true) {

            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


//            synchronized (obj){
//            synchronized (dog){
            synchronized (this) {
                if (ticket > 0) {

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "售票，票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }

        }


    }
}

public class WindowTest {
    public static void main(String[] args) {

        SaleTicket s = new SaleTicket();

        Thread t1 = new Thread(s);
        Thread t2 = new Thread(s);
        Thread t3 = new Thread(s);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();


    }
}

class Dog {

}